package pp.gateway.config.interceptor;

import com.alibaba.fastjson.JSON;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import pp.gateway.application.user.login.api.LoginService;
import pp.gateway.application.user.login.param.ParseTokenParam;

import java.util.List;

@Component
@Slf4j
public class PPInterceptor implements HandlerInterceptor {

    @Autowired
    LoginService loginService;
    @Value("${security.whiteList:/pp/user/login/loginByAccount,/pp/user/login/register,/static/**}")// 注入白名单配置
    private List<String> whitelist;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        try {
            String requestUri = request.getRequestURI();
            // 检查是否在白名单中
            if (isWhitelisted(requestUri)) {
                return true; // 放行白名单请求
            }
            // 鉴权逻辑（示例：检查请求头中的 Token）
            String token = request.getHeader("accessToken");
            ParseTokenParam param = new ParseTokenParam();
            param.setToken(token);
            if (token == null || loginService.parseToken(param)==null) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.getWriter().write("Unauthorized: Token is missing or invalid");
                log.info("{}.{} --> {};", this.getClass().getName(), new Object(){}.getClass().getEnclosingMethod().getName()
                        , "token无效 参数 token = " + JSON.toJSONString(token));
                return false; // 拦截请求
            }
        } catch (Exception e) {
            log.error("{}.{} --> {}", this.getClass().getName(), new Object(){}.getClass().getEnclosingMethod().getName()
                    , "拦截器系统异常");
        }
        return true; // 放行
    }

    /**
     * 检查请求路径是否在白名单中
     */
    private boolean isWhitelisted(String requestUri) {
        return whitelist.stream().anyMatch(requestUri::startsWith);
    }
}
